put.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
  2. import { UserService } from '@/server/modules/users/user.service';
  3. import { z } from '@hono/zod-openapi';
  4. import { authMiddleware } from '@/server/middleware/auth.middleware';
  5. import { ErrorSchema } from '@/server/utils/errorHandler';
  6. import { AppDataSource } from '@/server/data-source';
  7. import { AuthContext } from '@/server/types/context';
  8. import { UserSchema } from '@/server/modules/users/user.entity';
  9. const userService = new UserService(AppDataSource);
  10. const UpdateParams = z.object({
  11. id: z.coerce.number().openapi({
  12. param: { name: 'id', in: 'path' },
  13. example: 1,
  14. description: '用户ID'
  15. })
  16. });
  17. const UpdateUserSchema = UserSchema.omit({
  18. id: true,
  19. createdAt: true,
  20. updatedAt: true
  21. }).partial();
  22. const routeDef = createRoute({
  23. method: 'put',
  24. path: '/{id}',
  25. middleware: [authMiddleware],
  26. request: {
  27. params: UpdateParams,
  28. body: {
  29. content: {
  30. 'application/json': {
  31. schema: UpdateUserSchema
  32. }
  33. }
  34. }
  35. },
  36. responses: {
  37. 200: {
  38. description: '用户更新成功',
  39. content: { 'application/json': { schema: UserSchema } }
  40. },
  41. 400: {
  42. description: '无效输入',
  43. content: { 'application/json': { schema: ErrorSchema } }
  44. },
  45. 404: {
  46. description: '用户不存在',
  47. content: { 'application/json': { schema: ErrorSchema } }
  48. },
  49. 500: {
  50. description: '服务器错误',
  51. content: { 'application/json': { schema: ErrorSchema } }
  52. }
  53. }
  54. });
  55. const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  56. try {
  57. const { id } = c.req.valid('param');
  58. const data = c.req.valid('json');
  59. const user = await userService.updateUser(id, data);
  60. if (!user) {
  61. return c.json({ code: 404, message: '用户不存在' }, 404);
  62. }
  63. return c.json(user, 200);
  64. } catch (error) {
  65. return c.json({
  66. code: 500,
  67. message: error instanceof Error ? error.message : '更新用户失败'
  68. }, 500);
  69. }
  70. });
  71. export default app;